package com.zues.java_test.iptest;

import com.zues.java_test.juc_test.TPTInterrupt;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 设备心跳监控
 */
public class HeartbeatMonitor {

    private static final List<String> ipList = Arrays.asList("192.168.1.64", "192.168.1.65");
    private static final Map<String, Boolean> isConnectMap = new ConcurrentHashMap<>();
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        // 初始化 isConnectMap 中的所有条目
        ipList.forEach(ip -> isConnectMap.put(ip, false));

        Thread monitorThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(5000);
                    ipList.forEach(HeartbeatMonitor::checkDeviceConnection);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "摄像头心跳监控");
        monitorThread.start();
    }

    private static void checkDeviceConnection(String ip) {
        executorService.submit(() -> {
            if (TPTInterrupt.isConnect(ip)) {
                System.out.println(ip + "通讯已恢复");
                // 如果已经连接，则跳过
                if (Objects.nonNull(isConnectMap.get(ip)) && isConnectMap.get(ip)) {
                    return;
                }
                isConnectMap.put(ip, true);
                // 重新布放逻辑
                System.out.println(ip + "布放");
                return;
            }
            System.out.println(ip + "通讯断开");
            if (Objects.nonNull(isConnectMap.get(ip))) {
                if (isConnectMap.get(ip)) {
                    System.out.println("保存断开记录...");
                    isConnectMap.put(ip, false);
                }
                return;
            }
            isConnectMap.put(ip, false);
        });
    }
}
